<?php
/**
 * @author Artur Bier <izatop@gmail.com>
 * @package Files 
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
/**
 * FilesSingleRemoteUploader
 */

class FilesSingleRemoteUploader extends FilesSingleUploader implements IExecutable 
{
    protected $temporary;
    
    public function __construct($url = null, $savepath = null, FilesTypeFilter $typeFilter = null)
    {
        $this->savepath = $savepath;
        $this->type = array('mime' => null, 'ext' => mb_substr($url, -3));
        
        if($typeFilter instanceof FilesTypeFilter) {
            $this->setTypeFilter($typeFilter);
        }
        
        $this->temporary = "/tmp/" . uniqid('ud_') . ".{$this->type['ext']}";
        exec("fetch" . " -o " . escapeshellarg($this->temporary). " " . escapeshellarg($url), $output, $code);
        
        $tmp = explode('/', $url);
        $this->file = array(
            'name' => array_pop($tmp),
            'errno' => $code,
            'errmsg' => implode("\n", $output),
            'tmp_name' => $this->temporary,
        );
    }
    
    public function exec()
    {
        $filepath = $this->getSavePath();

        if(is_array($this->file['name'])) {
            throw new Exception('Files: invalid request');
        }
        
        if($this->file['errno']) {
            throw new Exception("Files: upload error (code {$this->file['errno']}) with message:\n" . $this->file['errmsg']);
        }

        if(!is_dir($this->savepath)) {
            exec('mkdir -p ' . escapeshellarg($this->savepath));
            if(!is_dir($this->savepath)) {
                throw new Exception('Files: cannot create directory (' . $this->savepath . ')');
            }
        }
        
        copy($this->file['tmp_name'], $filepath);
        chmod($filepath, Files::CHMOD_USERFILE);
        
        if($this->typeFilter instanceof FilesTypeFilter && !$this->typeFilter->check($filepath)) {
            unlink($filepath);
            throw new Exception('Files: invalid type (' . $this->typeFilter->getLastType() . ')');
        }
    }
    
    public function __destruct()
    {
        unlink($this->temporary);
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>